import sys
import asyncio
import qasync
from PyQt5.QtWidgets import QApplication
from 运行界面 import QyhtThinkUI
from 连接交易 import QMTTrader
from 行情监控 import MarketMonitor
import multiprocessing


def main():
    # 创建Qt应用
    app = QApplication(sys.argv)

    # 初始化交易实例
    trader = QMTTrader()
    
    market_monitor = MarketMonitor(trader=trader)  # 注入trader，log_callback后面由界面注入

    # 创建主窗口并注入依赖
    window = QyhtThinkUI(trader=trader, market_monitor=market_monitor)

    # 将交易实例传递给标题栏
    window.title_bar.trader = trader

    # 设置qasync事件循环
    loop = qasync.QEventLoop(app)
    asyncio.set_event_loop(loop)

    window.show()

    # 启动事件循环
    with loop:
        loop.run_forever()


if __name__ == "__main__":
    try:
        if sys.platform.startswith("win"):
            multiprocessing.freeze_support()
            try:
                multiprocessing.set_start_method('spawn', force=True)
            except RuntimeError:
                pass
        main()  # 直接调用同步main函数
    except Exception as e:
        print(f"程序启动失败: {e}")
        sys.exit(1)